package com.imooc.disruptor.heigh.chain;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.Data;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author yqc 2018/10/9
 */
@Data
public class TradePublisher implements Runnable {

    private CountDownLatch latch;
    private Disruptor<Trade> disruptor;

    private static int PUBLISH_COUNT = 1;

    public TradePublisher(CountDownLatch latch, Disruptor<Trade> disruptor) {
        this.latch = latch;
        this.disruptor = disruptor;
    }

    @Override
    public void run() {
        TradeEventTranslator tradeEventTranslator = new TradeEventTranslator();
        for (int i = 0; i < PUBLISH_COUNT; i++) {
            //新的提交任务的方式
            disruptor.publishEvent(tradeEventTranslator);
        }
        latch.countDown();
    }

    class TradeEventTranslator implements EventTranslator<Trade> {

        private Random random = new Random();

        @Override
        public void translateTo(Trade event, long sequence) {
            this.generateTrade(event);
        }

        private void generateTrade(Trade trade) {
            trade.setPrice(random.nextDouble() * 999);
        }
    }

}
